package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    private String lng_begin;
    private String lat_begin;
    private String lng_end;
    private String lat_end;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    private Orders orders;
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook address = addressBookMapper.getById(addressBookId);
        if (address==null)
        {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long currentId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(currentId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list==null || list.isEmpty())
        {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        String addressH=address.getProvinceName()+address.getCityName()+address.getDistrictName()+address.getDetail();
        System.out.println(addressH);
        //计算距离test（）
        int test = test("山东省淄博市周村区淄博职业学院南校区", addressH);
        if (test>5000)
        {
            throw new OrderBusinessException("配送距离过远");
//
        }
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(currentId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setUserName(address.getConsignee());
        orders.setPhone(address.getPhone());
        orders.setAddress(address.getProvinceName()+address.getCityName()+address.getDistrictName()+address.getDetail());
        orders.setConsignee(address.getConsignee());
        this.orders = orders;
        orderMapper.insert(orders);

        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insert(orderDetails);
        shoppingCartMapper.delete(shoppingCart);
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        return orderSubmitVO;
    }

    @Override
    public HistoryOrders historyOrders(String page, String pageSize, String status) {
        HistoryOrders historyOrders = new HistoryOrders();
        Long currentId = BaseContext.getCurrentId();
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(pageSize));
        Page<OrderVO> orderVOlist = (Page<OrderVO>) orderMapper.getOrders(currentId,status);
        for (OrderVO orderVO : orderVOlist) {
            List<OrderDetail> orderDetail=orderDetailMapper.getOrderDetailListByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetail);
        }
        historyOrders.setRecords(orderVOlist);
        historyOrders.setTotal(orderMapper.getOrders(currentId,status).size());
        return historyOrders;
    }

    @Override
    public OrderVO getdetail(String id) {
        OrderVO orderVO=orderMapper.selectById(id);
        List<OrderDetail> orderDetail=orderDetailMapper.getOrderDetailListByOrderId(orderVO.getId());
        orderVO.setOrderDetailList(orderDetail);
        LocalDateTime estimatedDeliveryTime = orderVO.getEstimatedDeliveryTime();
        return orderVO;
    }

    @Override
    public void cancel(String id) {
        orderMapper.updatestatus(id);
    }

    @Override
    public void repetition(String id) {
        OrderVO orderVO = orderMapper.selectById(id);
        orderVO.setStatus(Orders.PENDING_PAYMENT);
        orderVO.setOrderTime(LocalDateTime.now());
        orderVO.setEstimatedDeliveryTime(LocalDateTime.now().plusMinutes(60));
        orderVO.setNumber(String.valueOf(System.currentTimeMillis()));
        List<OrderDetail> orderDetailListByOrderId = orderDetailMapper.getOrderDetailListByOrderId(Long.valueOf(id));
        orderMapper.insert(orderVO);
        List<OrderDetail>newOrderDetailList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailListByOrderId) {
            orderDetail.setOrderId(orderVO.getId());
            newOrderDetailList.add(orderDetail);
        }
        orderDetailMapper.insert(newOrderDetailList);
    }

    @Override
    public void reminder(String id) {
        OrderVO orderVO = orderMapper.selectById(id);
        if (orderVO!=null)
        {
            Map map = new HashMap<>();
            map.put("type",2);
            map.put("orderid",id);
            map.put("content","订单号："+orderVO.getNumber());
            String jsonString = JSON.toJSONString(map);
            webSocketServer.sendToAllClient(jsonString);
        }
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        // 根据订单号查询订单信息（修复空指针问题）
        Orders orders = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        if (orders == null) {
            throw new OrderBusinessException("订单不存在");
        }

        // 模拟微信支付返回
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        Integer orderPaidStatus = Orders.PAID;        // 支付状态：已支付
        Integer orderStatus = Orders.TO_BE_CONFIRMED; // 订单状态：待接单
        LocalDateTime checkOutTime = LocalDateTime.now(); // 更新支付时间

        // 使用查询到的订单ID更新状态（修复空指针）
        orderMapper.updateStatus(orderStatus, orderPaidStatus, checkOutTime, orders.getId());

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);


    }

    public int test(String address_begin, String address_end) {
        String url = "https://api.map.baidu.com/geocoding/v3/?address="+address_begin+"&output=json&ak=HlkvXaQgkK2otVzymlMpWQK272zH6rzO";
        String url2 = "https://api.map.baidu.com/geocoding/v3/?address=+"+address_end+"&output=json&ak=HlkvXaQgkK2otVzymlMpWQK272zH6rzO";
        CloseableHttpClient httpClients = HttpClients.createDefault();
        HttpGet httpGet1 = new HttpGet(url);
        try {
            CloseableHttpResponse execute = httpClients.execute(httpGet1);
//            System.out.println(execute.getStatusLine().getStatusCode());
            HttpEntity entity = execute.getEntity();
            String responseBody = EntityUtils.toString(entity, "UTF-8");
//            System.out.println("完整响应体:\n" + responseBody);
            JSONObject jsonObject = JSONObject.parseObject(responseBody); // 再解析字符串
            JSONObject result = jsonObject.getJSONObject("result");
            JSONObject location = result.getJSONObject("location");
            lng_begin = location.getString("lng");
            lat_begin = location.getString("lat");
//            System.out.println(lng_begin+"--"+lat_begin);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HttpGet httpGet2 = new HttpGet(url2);
        try {
            CloseableHttpResponse execute = httpClients.execute(httpGet2);
//            System.out.println(execute.getStatusLine().getStatusCode());
            HttpEntity entity = execute.getEntity();
            String responseBody = EntityUtils.toString(entity, "UTF-8");
//            System.out.println("完整响应体:\n" + responseBody);
            JSONObject jsonObject = JSONObject.parseObject(responseBody); // 再解析字符串
            JSONObject result = jsonObject.getJSONObject("result");
            JSONObject location = result.getJSONObject("location");
            lng_end = location.getString("lng");
            lat_end = location.getString("lat");
//            System.out.println(lng_end+"--"+lat_end);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String url3 = "https://api.map.baidu.com/directionlite/v1/riding?origin="+lat_begin+","+lng_begin+"&destination="+lat_end+","+lng_end+"&ak=HlkvXaQgkK2otVzymlMpWQK272zH6rzO";
//        System.out.println(url3);
        HttpGet httpGet3 = new HttpGet(url3);
        int distance;
        try {
            CloseableHttpResponse execute = httpClients.execute(httpGet3);
//            System.out.println(execute.getStatusLine().getStatusCode());
            HttpEntity entity = execute.getEntity();
            String responseBody = EntityUtils.toString(entity, "UTF-8");
            System.out.println("完整响应体:\n" + responseBody);
            JSONObject jsonObject = JSONObject.parseObject(responseBody); // 再解析字符串
             distance = Integer.parseInt(jsonObject.getJSONObject("result")
                    .getJSONArray("routes").getJSONObject(0)
                    .getString("distance"));
            System.out.println("距离："+distance+"米");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return distance;
    }//计算两点间距离
}
